﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Code4WP7SDK;
using LuWeibo.Models;
using System.Collections.ObjectModel;
using LuWeiboSDK;
using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Text;

namespace LuWeibo.ViewModels
{
    public class SquareInfoViewModel : BaseModel
    {
        #region Fields
        private ObservableCollection<SquareModel> _squareInfos;
        private ObservableCollection<Status> _showStatuses;
        private SquareModel _selectedSquareModel;
        private ICommand _squareSelectCommand;
        private ObservableCollection<User> _interestUsers; //猜你喜欢
        private ICommand _createFriendShipCommand;  //创建关注关系
        private ICommand _cancelFriendShipCommand;  //取消关注关系
        private ICommand _goToStatusDetailCommand;  //跳转到微博详细页面
        private Status _selectedStatus;             //被选中的微博
        private User _selectedUser;
        private ICommand _goToUserDetailCommand;
        #endregion

        #region Properties
        public ObservableCollection<SquareModel> SquareInfos
        {
            get
            {
                if (this._squareInfos == null)
                {
                    this._squareInfos = new ObservableCollection<SquareModel> 
                    {
                        new SquareModel{SquareName = "热门转发",SquareImageUrl= "/Images/images_remenzhuanfa.png"},
                        new SquareModel{SquareName = "热门评论",SquareImageUrl= "/Images/images_remenpinglun.png"},
                        new SquareModel{SquareName = "随便看看",SquareImageUrl= "/Images/images_suibiankankan.png"},
                        new SquareModel{SquareName = "猜你喜欢",SquareImageUrl= "/Images/images_cainixihuan.png"}
                    };
                }
                return _squareInfos;
            }
            set
            {
                _squareInfos = value;
                this.NotifyPropertyChanged(p => p.SquareInfos);
            }
        }

        public ObservableCollection<Status> ShowStatuses
        {
            get
            {
                if (this._showStatuses == null)
                {
                    this._showStatuses = new ObservableCollection<Status>();
                }
                return _showStatuses;
            }
            set
            {
                _showStatuses = value;
                this.NotifyPropertyChanged(p => p.ShowStatuses);
            }
        }

        public ObservableCollection<User> InterestUsers
        {
            get
            {
                if (this._interestUsers == null)
                {
                    this._interestUsers = new ObservableCollection<User>();
                }
                return _interestUsers;
            }
            set
            {
                _interestUsers = value;
                this.NotifyPropertyChanged(p => p.InterestUsers);
            }
        }

        public SquareModel SelectedSquareModel
        {
            get { return _selectedSquareModel; }
            set
            {
                _selectedSquareModel = value;
                this.NotifyPropertyChanged(p => p.SelectedSquareModel);
                SquareSelectExecute(value);
            }
        }

        public Status SelectedStatus
        {
            get { return _selectedStatus; }
            set
            {
                _selectedStatus = value;
                this.NotifyPropertyChanged(p => p.SelectedStatus);
            }
        }

        public User SelectedUser
        {
            get { return _selectedUser; }
            set
            {
                _selectedUser = value;
                this.NotifyPropertyChanged(p => p.SelectedUser);
            }
        }
        #endregion

        #region Command
        public ICommand SquareSelectCommand
        {
            get
            {
                if (this._squareSelectCommand == null)
                {
                    this._squareSelectCommand = new BaseCommand<SquareModel>(SquareSelectExecute);
                }
                return _squareSelectCommand;
            }
        }

        public ICommand CreateFriendShipCommand
        {
            get
            {
                if (this._createFriendShipCommand == null)
                {
                    this._createFriendShipCommand = new BaseCommand<User>(CreateFriendShipExecute);
                }
                return _createFriendShipCommand;
            }
        }

        public ICommand CancelFriendShipCommand
        {
            get
            {
                if (this._cancelFriendShipCommand == null)
                {
                    this._cancelFriendShipCommand = new BaseCommand<User>(CancelFriendShipExecute);
                }
                return _cancelFriendShipCommand;
            }
        }

        public ICommand GoToStatusDetailCommand
        {
            get
            {
                if (this._goToStatusDetailCommand == null)
                {
                    this._goToStatusDetailCommand = new BaseCommand<Status>(GoToStausDetailExecute);
                }
                return _goToStatusDetailCommand;
            }
        }

        public ICommand GoToUserDetailCommand
        {
            get
            {
                if (this._goToUserDetailCommand == null)
                {
                    this._goToUserDetailCommand = new BaseCommand<User>(GoToUserDetailExecute);
                }
                return _goToUserDetailCommand;
            }
        }
        #endregion

        #region Method
        public void SquareSelectExecute(SquareModel selectedModel)
        {
            if (selectedModel == null)
            {
                return;
            }
            if ("热门转发".Equals(selectedModel.SquareName))
            {
                this.ShowStatuses.Clear();
                string data = ParameterHelper.BuildParameters(new List<Parameter>());
                WebClientService ws = new WebClientService();
                ws.WebClientCompleted += (s, e) =>
                {
                    if (e.Ex == null)
                    {
                        //Debug.WriteLine(e.Result.ToString());
                        //反序列化
                        this.ShowStatuses = JsonConvert.DeserializeObject<ObservableCollection<Status>>(e.Result.ToString());
                        VmNavigateHelper.Navigate("/Views/LuHomePage.xaml", "/Views/Square/SquareDetailPage.xaml?moudleName=" + selectedModel.SquareName);
                    }
                    else
                    {
                        //获取当天的热门评论转发出错
                    }
                };
                ws.GetRequest(Urls.statuses_hot_repost_daily, data);
            }
            else if ("热门评论".Equals(selectedModel.SquareName))
            {
                this.ShowStatuses.Clear();
                string data = ParameterHelper.BuildParameters(new List<Parameter>());
                WebClientService ws = new WebClientService();
                ws.WebClientCompleted += (s, e) =>
                {
                    if (e.Ex == null)
                    {
                        //Debug.WriteLine(e.Result.ToString());
                        //反序列化
                        this.ShowStatuses = JsonConvert.DeserializeObject<ObservableCollection<Status>>(e.Result.ToString());
                        VmNavigateHelper.Navigate("/Views/LuHomePage.xaml", "/Views/Square/SquareDetailPage.xaml?moudleName=" + selectedModel.SquareName);
                    }
                    else
                    {
                        //获取当天的热门评论转发出错
                    }
                };
                ws.GetRequest(Urls.statuses_hot_comments_daily, data);
            }
            else if ("随便看看".Equals(selectedModel.SquareName))
            {
                int type = new Random().Next(1,10);
                List<Parameter> paras = new List<Parameter>();
                paras.Add(new Parameter("type",type));
                paras.Add(new Parameter("is_pic", 1));
                string data = ParameterHelper.BuildParameters(paras);
                WebClientService ws = new WebClientService();
                ws.WebClientCompleted += (s, e) =>
                {
                    if (e.Ex == null)
                    {
                        //Debug.WriteLine(e.Result.ToString());
                        //反序列化
                        JObject jobj = JObject.Parse(e.Result.ToString());
                        IList<JToken> results = jobj["statuses"].Children().ToList();
                        foreach (JToken result in results)
                        {
                            JToken jt = JObject.Parse(result.ToString())["status"] as JToken;
                            Status status = JsonConvert.DeserializeObject<Status>(jt.ToString());
                            this.ShowStatuses.Add(status);
                        }
                        VmNavigateHelper.Navigate("/Views/LuHomePage.xaml", "/Views/Square/SquareDetailPage.xaml?moudleName=" + selectedModel.SquareName);
                    }
                    else
                    {
                        //获取当天的热门评论转发出错
                    }
                };
                ws.GetRequest(Urls.suggestions_statuses_hot, data);
            }
            else if ("猜你喜欢".Equals(selectedModel.SquareName))
            {
                string data = ParameterHelper.BuildParameters(new List<Parameter>());
                WebClientService ws = new WebClientService();
                ws.WebClientCompleted += (s, e) =>
                    {
                        if (e.Ex == null)
                        {
                            Debug.WriteLine(e.Result.ToString());
                            List<string> uids = new List<string>();
                            using (JsonHelper jhelper = new JsonHelper(e.Result.ToString()))
                            {
                                for (int i = 0; i < jhelper.Count(); i++)
                                {
                                    jhelper.at(i);
                                    string uid = jhelper.get<string>("uid");
                                    uids.Add(uid);
                                    jhelper.up();
                                }
                            }
                            GetInterestUsers(uids);
                            VmNavigateHelper.Navigate("/Views/LuHomePage.xaml", "/Views/Square/GuessYouLikePage.xaml");
                            //更具UID请求用户数据
                        }
                        else
                        {
                            //获取猜你喜欢信息失败
                        }
                    };
                ws.GetRequest(Urls.suggestions_users_may_interested,data);
            }
            this.SelectedSquareModel = null; //把选中项重置这样可以支持选中同样的信息
        }

        private void GetInterestUsers(List<string> uids) 
        {
            foreach (string uid in uids)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("&{0}={1}", "access_token", Constant.AccessToken);
                sb.AppendFormat("&{0}={1}", "uid", uid);
                string data = sb.ToString().Substring(1);
                WebClientService ws = new WebClientService();
                ws.WebClientCompleted += (s, e) =>
                {
                    if (e.Ex == null)
                    {
                        //Debug.WriteLine(e.Result.ToString());
                        User user = JsonConvert.DeserializeObject<User>(e.Result.ToString());
                        this.InterestUsers.Add(user);
                    }
                    else
                    {
                        //获取感兴趣的用户信息出错了
                    }
                };
                ws.GetRequest(Urls.users_show, data);
            }
        }

        public void CreateFriendShipExecute(User selectedUser)
        {
            if (selectedUser != null)
            {
                List<Parameter> paras = new List<Parameter>();
                paras.Add(new Parameter("screen_name", selectedUser.screen_name));
                string data = ParameterHelper.BuildParameters(paras);
                WebClientService ws = new WebClientService();
                ws.WebClientCompleted += (s, e) =>
                    {
                        if (e.Ex == null)
                        {
                            Debug.WriteLine(e.Result.ToString());
                        }
                        else
                        {
                            //关注用户失败
                        }
                    };
                ws.PostRequest(Urls.friendships_create, data);
            }
        }

        /// <summary>
        /// 取消关注用户
        /// </summary>
        /// <param name="selectedUser"></param>
        public void CancelFriendShipExecute(User selectedUser)
        {
            if (selectedUser != null)
            {
                List<Parameter> paras = new List<Parameter>();
                paras.Add(new Parameter("screen_name", selectedUser.screen_name));
                string data = ParameterHelper.BuildParameters(paras);
                WebClientService ws = new WebClientService();
                ws.WebClientCompleted += (s, e) =>
                {
                    if (e.Ex == null)
                    {
                        Debug.WriteLine(e.Result.ToString());
                    }
                    else
                    {
                        //关注用户失败
                    }
                };
                ws.PostRequest(Urls.friendships_destroy, data);
            }
        }
        /// <summary>
        /// 根据选中的微博跳转到微博详细页面
        /// </summary>
        /// <param name="selectedStatus"></param>
        public void GoToStausDetailExecute(Status selectedStatus)
        {
            if (selectedStatus != null)
            {
                ViewModelLocator.StatusDetailVMStatic.CurrentStatus = selectedStatus;
                VmNavigateHelper.Navigate("/Views/Square/SquareDetailPage.xaml", "/Views/Status/StatusDeatailPage.xaml");
                this.SelectedStatus = null;
            }
        }

        public void GoToUserDetailExecute(User selectedUser)
        {
            if (selectedUser != null)
            {
                VmNavigateHelper.Navigate("/Views/Square/GuessYouLikePage.xaml", "/Views/Profile/UsersStatusPage.xaml?uid=" + Convert.ToInt64(selectedUser.id));
                selectedUser = null;
            }
        }
        #endregion
    }
}
